package mao.leetcode.others.leetcode107;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution {
    /*
    亦可以求出层次中的个数，然后再进行遍历；
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> lists = new LinkedList<>();
        if (root == null) return lists;
        ArrayList<Integer> l = new ArrayList<>();
        queue.offer(root);
        queue.offer(null);  //使用null进行层次之间的隔断
        while (  queue.size() > 1){
            TreeNode node = queue.poll();
            if (node != null){
                if (node.left != null)  queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
                l.add(node.val);
            }else {
                lists.add(0,l);
                queue.offer(null);
                l=new ArrayList<Integer>();
            }
        }
        lists.add(0,l);  //把最后一个加入进来
        return lists;
    }



    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
    }
}
